<template>
  <div class="Book">
<!--    添加书籍按钮-->
    <el-button
      @click="
      formDialogVisible = true;
      isEdit = false;">
      添加书籍
    </el-button>
<!--书籍表格-->
    <div class="bookTable">
      <el-table :data="bookList" border style="width: 100%">
        <el-table-column label="序号" width="150" type="index">
        </el-table-column>
        <el-table-column prop="img" label="封面" width="300">
          <template slot-scope="scope">
            <img class="pic" :src="scope.row.img" alt="封面" />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="名称" width="300">
        </el-table-column>
        <el-table-column  label="详情" width="240">
          <template slot-scope="scope">
          <el-button type = "text" @click="chapterDetail(scope.row.id)">查看章</el-button>  
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template slot-scope="scope">
            <el-button
              @click="updateBook(scope.row)"
              type="text"
              size="small">编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="deleteBook(scope.row.id,scope.row.img)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--添加/编辑书籍表单-->
    <div class="formDialog">
      <el-dialog
          :title="dialogTitle"
          :visible.sync="formDialogVisible"
          width="50%"
          :before-close="handleClose">
        <el-form ref="form" :model="bookForm" label-width="80px" :rules="bookFormRules">
          <el-form-item label="上传封面">
            <el-upload
                :action="getUploadURL()"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :file-list="fileList">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogImgVisible">
              <img width="100%" :src="dialogImageUrl" alt="封面图" />
            </el-dialog>
          </el-form-item>
          <el-form-item label="书籍名称" prop="title">
            <el-input v-model="bookForm.title"></el-input>
          </el-form-item>
          <el-form-item label="排序权重" prop="orderby">
            <el-input v-model="bookForm.orderby"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import request from "../utils/request";
export default {
  data() {
    return {
      // 控制添加、编辑表单的显示与隐藏
      formDialogVisible: false,
      dialogImgVisible: false,
      // 标识处于编辑还是添加状态
      isEdit: false,

      dialogImageUrl: "",
      // 获取到的图片地址
      imageUrl: "",
      // 书籍列表
      bookList: [],
      // 上传文件列表
      fileList: [],
      // 书籍表单
      bookForm: {
        title: "",
        orderby: "",
        img: "",
      },
      //书籍表单的验证规则
      bookFormRules:{
        title:[{required:true,message:"请输入标题",trigger:"blur"}],
        orderby: [{required:true,message:"请输入书籍的排序权重",trigger:"blur"}]
      }
    };
  },
  methods: {
    // 添加/编辑表单关闭事件
    handleClose() {
      this.$refs.form.resetFields();
      this.bookForm.img = "";
      this.bookForm.title = "";
      this.bookForm.orderby = "";
      this.fileList = [];
      this.formDialogVisible = false;
    },
    //移除文件
    handleRemove({response}, fileList) {
      this.deleteimg(response.data.file)
    },
    //预览文件
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogImgVisible = true;
    },
    //图片上传成功后的回调
    handleSuccess(response) {
      if (response.code === 20000) {
        this.bookForm.img = response.data.file;
      }
    },
    // 提交表单
    onSubmit() {
      this.$refs.form.validate(async valid=>{
        if(valid) {
          if (!this.isEdit) {
            // 增加图书
            const {data: res} = await request.post("book", {
              title: this.bookForm.title,
              orderby: this.bookForm.orderby,
              img: this.bookForm.img,
            })
            if (res.code === 20000) {
              this.getBookList();
              this.$message.success("添加书籍成功");
              this.fileList = [];
              this.formDialogVisible = false;
            } else {
              this.$message.success("添加书籍失败")
            }
          } else {
            //修改图书
            const {data: res} = await request.put(`book/${this.id}`, {
              title: this.bookForm.title,
              img: this.bookForm.img,
              orderby: this.bookForm.orderby,
            })
            if (res.code === 20000) {
              this.getBookList();
              this.isEdit = false;
              this.formDialogVisible = false;
              this.$message.success("修改书籍成功")
            }
          }
        }
        })
    },
    //获取图书列表
    getBookList() {
     request.get(`book?page=1&total=100`).then((res)=>{
       if(res.data.code === 20000){
         this.bookList = res.data.data;
       }else{
         this.$message.error("获取书籍列表失败")
       }
     })

    },

    //删除图书
    deleteBook(id,img) {
        this.$confirm("确认删除？")
        .then(async () => {
          const {data:res} = await request.delete(`book/${id}`)
            if (res.code === 20000) {
              this.deleteimg(img)
              this.$message.success("删除成功")
              this.getBookList();
        }else{
              this.$message.error("删除失败")
            }
      })
        .catch(() => {
          this.$message.info("取消删除")
        });
     
    },
    //更新图书
    updateBook(row) {
      this.id = row.id;
      this.bookForm.orderby = row.orderby;
      this.bookForm.title = row.title;
      this.bookForm.img = row.img;
      this.fileList = [{ url: row.img }];
      this.isEdit = true;
      this.formDialogVisible = true;
    },

    //查看章
    chapterDetail(id){
      this.$router.push(`/chapter?book_id=${id}`)
    },
    //获取上传连接
    getUploadURL() {
      return `${process.env.VUE_APP_BASE_API}upload`;
    },
    // 删除封面
    deleteimg(img){
      let arr = img.split("/")
      let target = arr[arr.length-1]
      request({
        method:"delete",
        url:`/unlink/${target}`
      })
    }
  },
  computed:{
    dialogTitle(){
      return this.isEdit?"编辑书籍":"添加书籍"
    }
  },
  mounted() {
    this.getBookList();
  },

};
</script>


<style scoped>
.pic {
  width: 50px;
  height: 50px;
}
.bookTable{
  margin-top:20px ;
}
</style>

